package com.chs.recoginition.controller;


import com.alibaba.fastjson.JSONObject;
import com.chs.recoginition.core.utils.UploadUtil;
import com.chs.recoginition.pojo.Userinfo;
import com.chs.recoginition.pojo.WebSocketMessageResult;
import com.chs.recoginition.service.IUserinfoService;
import com.chs.recoginition.vo.JwtResource;
import com.chs.recoginition.vo.PageRespVo;
import com.chs.recoginition.vo.Result;
import com.chs.recoginition.vo.auth.LoginVo;
import com.chs.recoginition.vo.auth.UserPasswordUpdateVo;
import com.chs.recoginition.vo.reqvo.*;
import com.chs.recoginition.vo.respVo.UserInfoRespVo;
import com.chs.recoginition.vo.respVo.UserRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 * seckill
 * @author CHS
 * @since 2022-07-23
 */
@RestController
@RequestMapping("/userinfo")
@Slf4j
@CrossOrigin
public class UserinfoController extends BaseController{
    @Resource
    private IUserinfoService iUserinfoService;
    @Resource
    private JwtResource jwtResource;

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public Result<UserRespVo> login(@RequestBody @Valid LoginVo loginVo) {

        UserRespVo resultMap = iUserinfoService.login(loginVo);
        return Result.success(resultMap);
    }


    /**
     * 查询当前用户
     * @return
     */
    @RequestMapping(value = "/getUserInfo",method = RequestMethod.POST)
    private Result<UserRespVo> getUserInfo(@RequestBody String jsonStr){
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String token = jsonObject.get("token").toString();
        String userOpenId = jwtResource.getUsernameByToken(token);
        UserRespVo result = iUserinfoService.getUserByUsername(userOpenId);
        return Result.success(result);
    }





    /**
     * 添加用户
     * @return
     */
    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    private Result<Void> save(@RequestBody Userinfo userinfo){
        Integer userOpenId = getUserOpenId();
        userinfo.setCreatedBy(userOpenId);
        iUserinfoService.saveInfo(userinfo,getUser());
        return Result.success();
    }

    /**
     * 修改用户密码信息
     * @param updateVo
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody @Valid UserPasswordUpdateVo updateVo) {
        // 修改用户密码
        iUserinfoService.updatePassword(updateVo);
        return Result.success();
    }

    /**
     * 删除用户
     * @param jsonStr id列表
     * @return
     */
    @PostMapping("/remove")
    public Result remove(@RequestBody String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String idList = jsonObject.get("idList").toString();
        // 删除用户
        iUserinfoService.remove(idList);
        return Result.success();
    }

    /**
     * 修改用户
     * @return
     */
    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    private Result<Void> modify(@RequestBody Userinfo userinfo){
        Integer userOpenId = getUserOpenId();
        userinfo.setUpdatedBy(userOpenId);
        iUserinfoService.modify(userinfo,getUser());
        return Result.success();
    }

    /**
     * 当前登录用户
     */
    @PostMapping("/user")
    public Result user(HttpServletRequest request) {
        // 获取登陆token
        String token = request.getParameter("token");
        LinkedHashMap userVo = jwtResource.getUserVoByToken(token);
        return Result.success(userVo);
    }


    /**
     * 分页查询
     * @param reqVo
     * @return
     */
    @RequestMapping(value = "/getPage",method = RequestMethod.POST)
    private Result<PageRespVo<UserInfoRespVo>> getAllPage( UserinfoReqVo reqVo){
        PageRespVo<UserInfoRespVo> result = iUserinfoService.getAllPage(reqVo);
        return Result.success(result);
    }

    /**
     * 查询频道消息
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/getRedisMessageList",method = RequestMethod.POST)
    private Result<List<WebSocketMessageResult>> getRedisMessageList(@RequestBody String jsonStr){
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String channelNum = jsonObject.get("channelNum").toString();
        List<WebSocketMessageResult> result = iUserinfoService.getRedisMessageList(channelNum);
        return Result.success(result);
    }

    /**
     * 通过邮箱注册用户
     * @return
     */
    @RequestMapping(value = "/sendEmailCodeByReg",method = RequestMethod.POST)
    private Result<Void> sendEmailCodeByReg(@RequestBody String jsonStr){
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String username = jsonObject.get("username").toString();
        String email = jsonObject.get("email").toString();
        iUserinfoService.sendEmailCodeByReg(username,email);
        return Result.success();
    }
    /**
     * 通过邮箱注册用户
     * @return
     */
    @RequestMapping(value = "/userReg",method = RequestMethod.POST)
    private Result<Void> userReg(@RequestBody @Valid UserRegReqVo reqVo){
        iUserinfoService.saveUserReg(reqVo);
        return Result.success();
    }

    /**
     * 发送邮件修改密码 获得验证码
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/sendEmailCode",method = RequestMethod.POST)
    private Result<Void> sendEmailCode(@RequestBody String jsonStr){
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String username = jsonObject.get("username").toString();
        iUserinfoService.sendEmailCode(username);
        return Result.success();
    }

    /**
     * 根据验证码修改密码
     * @param userPasswordByCodeReqVo
     * @return
     */
    @RequestMapping(value = "/updatePasswordByEmailCode",method = RequestMethod.POST)
    private Result<Void> updatePasswordByEmailCode(@RequestBody @Valid UserPasswordByCodeReqVo userPasswordByCodeReqVo){
        iUserinfoService.updatePasswordByEmailCode(userPasswordByCodeReqVo);
        return Result.success();
    }


    /**
     * 查找用户邮箱
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/findUserEmail",method = RequestMethod.POST)
    private Result<String> findUserEmail(@RequestBody String jsonStr){
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String userOpenId = jsonObject.get("userOpenId").toString();
        String result = iUserinfoService.findUserEmail(userOpenId);
        return Result.success(result);
    }

    /**
     * 上传头像
     * @param
     * @return
     */
    @RequestMapping(value = "/uploadUserHeadImage",method = RequestMethod.POST)
    private Result<String> uploadUserHeader(HttpServletResponse response,MultipartFile file) throws IOException {
        System.out.println(file);
        String result = iUserinfoService.uploadUserHeader(response,file);
        result = UploadUtil.localhost + "/userinfo/toUserHeadImage" + "/" +result;
        return Result.success(result);
    }

    @RequestMapping(value="/toUserHeadImage/images/head/{fileName:.+}",method=RequestMethod.GET)
    public void doPost(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //读取本地图片输入流
//        System.out.println(fileName);
//        FileInputStream inputStream = new FileInputStream("F:\\ftp\\"+fileName);
        FileInputStream inputStream = new FileInputStream(UploadUtil.getRootPath()+"/images/head/"+fileName);
        int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //记得关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setContentType("image/*");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();
    }

}
